import os
import json
import sys
from pathlib import Path

# Ensure Redis snapshot verification is enabled even without redis package
os.environ.setdefault("REDIS_ENABLED", "true")

# Ensure project root in sys.path
PROJ_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJ_ROOT))

from api.dao.db import init_db
from api.routers.dto.flow_create import FlowCreate
from api.routers.dto.flow_data import FlowData
from api.routers.dto.run_params import RunParams
from api.services.flows_service import create_flow_service, run_flow_service
from api.dao import runs_dao, flows_dao


def main():
    print(f"[INFO] Python={sys.version}")
    print(f"[INFO] sys.path[0]={sys.path[0]}")

    # Initialize DB schema
    init_db()
    print("[INFO] DB initialized")

    # Load example flow definition
    example_path = PROJ_ROOT / "examples" / "http_flow.json"
    print(f"[INFO] Loading example: {example_path}")
    flow_def = json.loads(example_path.read_text(encoding="utf-8"))

    # Ensure a flow exists: try reuse existing by name to avoid UNIQUE constraint error
    flow_name = "http_flow_demo"
    existing = next((f for f in flows_dao.list_flows() if f.get("name") == flow_name), None)
    if existing:
        flow_id = existing["id"]
        print(f"[INFO] Reusing existing flow_id={flow_id} for name='{flow_name}'")
    else:
        # Create flow via service
        payload = FlowCreate(name=flow_name, description="demo via service", flow=FlowData(**flow_def))
        try:
            flow_id = create_flow_service(payload)
            print("[INFO] flow_id=", flow_id)
        except Exception as ce:
            print(f"[WARN] create_flow_service failed: {ce}. Attempting to reuse existing record if present...")
            existing = next((f for f in flows_dao.list_flows() if f.get("name") == flow_name), None)
            if not existing:
                raise
            flow_id = existing["id"]
            print(f"[INFO] Reused existing flow_id={flow_id}")

    # Build run params
    params = RunParams(
        engine="flow",
        max_steps=1000,
        context={
            "event": {"eventCode": "HTTP_DEMO", "eventSource": "local", "data": {"q": "ping"}},
            "request": {"source": "service_demo"},
        },
    )

    # Run via service (get run_id and task), then execute synchronously
    run_id, task = run_flow_service(flow_id, params)
    print("[INFO] run_id=", run_id)
    print("[INFO] Executing task synchronously...")
    task()
    print("[INFO] Task execution finished")

    # Fetch run record from DB to inspect context/trace persisted by runner
    run_rec = runs_dao.get_run(run_id)
    if run_rec:
        ctx = run_rec.get("context") or {}
        trace = run_rec.get("trace") or []
        print("[RESULT] status=", run_rec.get("status"))
        print("[RESULT] trace_len=", len(trace))
        print("[RESULT] context keys:", list(ctx.keys()))
        nodes = ctx.get("nodes", {})
        print("[RESULT] nodes_len=", len(nodes))
        if nodes:
            first_key = next(iter(nodes.keys()))
            print("[RESULT] sample node record:", nodes[first_key])
    else:
        print("[WARN] Failed to fetch run record from DB")

    # Verify Redis snapshot using fallback in-memory client if real Redis isn't installed
    try:
        from api.config.redis_config import get_redis_settings
        settings = get_redis_settings()
        from api.managers.redis_manager import REDIS_MANAGER
        key = f"{run_id}_context"
        if settings.enabled:
            print(f"[INFO] REDIS_ENABLED=true, reading key: {key}")
            ctx_json = REDIS_MANAGER.get_json(key)
            if ctx_json:
                keys = list(ctx_json.keys())
                print("[REDIS] context keys:", keys)
                nodes = ctx_json.get("nodes", {})
                print("[REDIS] nodes_len=", len(nodes))
                # Simple validation
                print("[CHECK] has nodes?", "nodes" in ctx_json)
            else:
                print("[REDIS] No context found for key", key)
        else:
            print("[INFO] REDIS_ENABLED=false, skipping Redis verification.")
    except Exception as ex:
        print(f"[INFO] Redis not available or import failed: {ex}")

    print("DONE")


if __name__ == "__main__":
    main()